<?php

namespace app\index\controller;

use app\admin\model\Admin;
use app\admin\library\Auth;
use app\admin\model\agent\Express;
use app\admin\model\Assistant as AssistantModel;
use app\admin\model\Githouse;
use app\common\controller\Frontend;
use app\common\model\order\Order;
use app\common\model\order\Orderitem;
use app\admin\model\Preproduct;
use app\common\model\Warehouse;
use EasyWeChat\Factory;
use think\Db;
use think\Session;
use app\common\model\order\Orderlog;
use app\common\library\Upload;
use app\admin\model\AdminLog;
use fast\Http;
use think\Cache;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Validate;
use think\Lang;
class Agent extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    protected $flow;
    protected $login_url;

    public function _initialize()
    {

        $this->auth = Auth::instance();
        $this->config = AssistantModel::config();
        $this->login_url = "/index/agent/oauth/order/";
        // 检测是否需要验证登录
         if($_SERVER['SERVER_NAME'] != 'oa.fc62.com'){
            $this->login_url = "/index/agent/userLogin/order/";
         }
         $this->loadlang("/login",'agent');
    }
    public function userLogin($order = null){
        
        $url = $this->request->get('url', '/index/agent/details/orderID/'.$order);
        if ($this->auth->isLogin()) {
          
            $this->success(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost()) {
           
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:2,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle("要货审核登录");
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
   }
   
    public function login()
    {
        $app = Factory::work(AssistantModel::config($this->config));

        $token = $app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $orderid = $this->request->request('state');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);
        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
               if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    return redirect('/index/agent/details/orderID/'.$orderid);
                }
            
            }
        }else{
            return redirect($this->request->domain().'/index/agent/oauth');
        }
    }

    public function oauth($order){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state={$order}#wechat_redirect";
        return redirect($url);
    }

   /**
     * 图书对接人审核
     * @author 杨柳
     * @date   2019-06-04 11:07:04
     */
    public function details($orderID = null)
    {
//        Session::set('agent_admin',Admin::get(['userid'=>'yangliu']));
        if(!$this->auth->isLogin())
        {
            return redirect($this->request->domain().$this->login_url.$orderID);
        }
        $order = Order::get($orderID);

        if(!$order) $this->error('订单不存在');
        $log = Orderlog::where(['dep_id'=>$order['dep_id'],'order_id'=>$orderID])->select();
        foreach ($log as $key => &$value) {
            $value->avatar = TableField('Admin','avatar',$value['userid'],'userid');
            # code...
        }
        //print_r($log);die;
        $order['log'] = $log;
        unset($value);
        //分公司数据
        $agent = Githouse::get(array('id'=>$order['dep_id']));
        $userinfo = Admin::get(array('userid'=>$order['userid']));
        //上线就显示
        /**/
        if($order->status == '-1' || !check_public($orderID,1,$this->auth)){
            //已经结束审核
            $this->redirect('view',['ids'=>$orderID]);
        }
        //审核页面   所有的数据、
        $this->view->assign('admin',$this->auth);
        $this->view->assign('userinfo',$userinfo);
        //订单详情
        $order['image'] = unserialize($order['image']);
        $orderItem = Orderitem::alias('a')
            ->field('a.*,a.remark as remarks,b.type,b.cname,b.b_n')
            ->where('a.order_id',$orderID)
            ->join('hdyj_preproduct b','a.preproduct_id = b.id')
            ->select();
        $agent['warehouse'] = Warehouse::where(['agent_id'=>$agent['id'],'status'=>1])->find();
     
        $this->view->assign('order',$order);
        $this->view->assign('agent',$agent);
        $this->view->assign('orderItem',$orderItem);
        //获取物流信息
        $this->view->assign('express',Express::where(['statuswitch'=>1])->select());
        //获取仓库信息
        $this->view->assign('githouse',Githouse::where('status','=',1)->select());
        return $this->view->fetch('agent/'.\think\Config::get('review.check')[$order->sorter]['step'][$order->step]['action']);
    }


    /**
     * 审核 通过 驳回 提交
     * @return mixed
     */
    public function do_check_save()
    {
        $data = $this->request->param();
        $order = Order::get($data['orderID']);
        if(!$order) $this->error('订单不存在');

        /*上线就显示*/
        if($order->status == '-1'  || !check_public($data['orderID'],1,$this->auth)){
            //已经结束审核
           return $this->redirect('view',['ids'=>$data['orderID']]);
        }
        $save = ['content'=>$data['content']];

        //驳回
        if($data['submit_to_save'] == 'no')
        {
            $save['save'] = 2;
            //驳回
            check_public($data['orderID'],1,$this->auth,$save);
            check_public($data['orderID'],6,$this->auth);
            return $this->redirect("/index/agent/details",['orderID'=>$data['orderID']]);
        }
  
        //选择的仓库
        if($git = $this->request->request('git'))
        {
               //是否有图片上传
            if ($this->request->file('file')) {
                $files = $this->request->request('file_base/a');
                $save['deliverys_image'] = serialize($files);
            }
            $agent = Githouse::get(array('id'=>$order['dep_id']));
            if(!$agent) $this->error('您的仓库不存在！！ 请联系管理员');
            $resout = $this->githouse($agent->id,$order->id,$this->auth->userid);
            if (!$resout)
            {
                $this->error('数据错误');
            }else{
              if(!$resout['status']){
                    $preRow = Preproduct::get($resout['id']);
                    $this->error($preRow->cname.'库存不足，请联系库房添加库存！');
                }else{
                     //订单修改 发货单id
                    $save['delivery_id'] = $resout['order_id'];
                }
            }
        }
        $save['save'] = 1;
        //发送通知给下一个审核人
        check_public($data['orderID'],1,$this->auth,$save);
        check_public($data['orderID'],6,$this->auth);
        return $this->redirect("/index/agent/details",['orderID'=>$data['orderID']]);
    }

    /**
     * 审核完成
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function view($ids)
    {
        //订单详情
        $order = Order::get($ids);
        if(!$order) $this->error('订单不存在');
        $log = Orderlog::where(['dep_id'=>$order['dep_id'],'order_id'=>$ids])->select();
        foreach ($log as $key => &$value) {
            $value->avatar = TableField('Admin','avatar',$value['userid'],'userid');
            # code...
        }
        //print_r($log);die;
        $order['log'] = $log;
        unset($value);
        $agent = Githouse::get(array('id'=>$order['dep_id']));
        $userinfo = Admin::get(array('userid'=>$order['userid']));
        $orderItem = Orderitem::alias('a')
            ->field('a.*,a.remark as remarks,b.type,b.cname,b.b_n')
            ->where('a.order_id',$ids)
            ->join('hdyj_preproduct b','a.preproduct_id = b.id')
            ->select();
        $agent['warehouse'] = Warehouse::where(['agent_id'=>$agent['id'],'status'=>1,'sorter'=>1])->find();
        $this->view->assign('order',$order);
        $this->view->assign('agent',$agent);
        $this->view->assign('userinfo',$userinfo);
        $this->view->assign('orderItem',$orderItem);
        return $this->view->fetch();
    }



    /**
     * 代理商订单出库
     * @param $orderId
     * @param $userid
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function githouse($githouse,$orderId,$userid)
    {
        $orderItem =  Orderitem::alias('a')
            ->field('a.*,a.remark as remarks,b.type,b.cname,b.b_n')
            ->where('a.order_id',$orderId)
            ->join('hdyj_preproduct b','a.preproduct_id = b.id')
            ->select();

        $list = [];
        foreach ($orderItem as $value)
        {
            $list[] = ['id'=>$value['preproduct_id'],'num'=>$value['num']];
        }
        $response = gzy_reduce_stock($githouse,$list,$userid);
        return $response;
    }

    public function logout()
    {
        Session::set('agent_admin','');
        echo "退出登录";exit;
    }
    public function upload(){
        //是否有图片上传
        if ($this->request->request('file')) {
            $upload = new Upload();
            $upload->path(ROOT_PATH.'public/agent/upload');//上传 发货凭证
            $file = $upload->upbase($this->request->request('file'));
            if($file){
                 $this->success('操作成功','',$file);
            }else{
                 $this->error($upload->error());
            }
        }
    }
}
